/*
 * Created by: xwc
 * Date: 2018
 * e-mail: xwencong@163.com
 */

package com.partners.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.util.*;

/**
 * Spring上下文管理工具类
 *
 * @author xwencong@163.com
 * @date 2018/7/9 14:42
 */
public class SpringContextUtil {

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    public static <T> List<T> listBean(Class<T> clazz) {
        List<T> beans = null;

        Map<String, T> beanMap = getApplicationContext().getBeansOfType(clazz);

        if(!beanMap.isEmpty()) {
            beans = new ArrayList<>(beanMap.size());
            Set<Map.Entry<String, T>> entrySet = beanMap.entrySet();
            Iterator<Map.Entry<String, T>> beanIterator = entrySet.iterator();
            while (beanIterator.hasNext()) {
                Map.Entry<String, T> entry = beanIterator.next();
                beans.add(entry.getValue());
            }
        }

        return beans;
    }


}
